package com.snail.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.snail.mapper.SysDeptMapper;
import com.snail.mapper.SysUserMapper;
import com.snail.model.dto.user.DeptQueryDTO;
import com.snail.model.dto.user.DeptSaveDTO;
import com.snail.model.dto.user.RemarkHistory;
import com.snail.model.dto.user.RemarkInfo;
import com.snail.model.pojo.user.SysDept;
import com.snail.model.pojo.user.SysUser;
import com.snail.model.vo.user.DeptVO;
import com.snail.result.Result;
import com.snail.service.SysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;



/**
 * @author Administrator
 * @description 针对表【sys_dept(部门表)】的数据库操作Service实现
 * @createDate 2024-07-09 16:11:56
 */
@Service
@Slf4j
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    
    private final SysUserMapper userMapper;
    
    public SysDeptServiceImpl(SysUserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 分页查询部门信息
     * @param page 分页参数
     * @param queryDTO 查询条件
     * @return
     */
    @Override
    public IPage<DeptVO> queryDeptPage(Page<SysDept> page, DeptQueryDTO queryDTO) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.hasText(queryDTO.getName())) {
            wrapper.like(SysDept::getName, queryDTO.getName());
        }
        if (StringUtils.hasText(queryDTO.getCode())) {
            wrapper.like(SysDept::getCode, queryDTO.getCode());
        }
        if (queryDTO.getStatus() != null) {
            wrapper.eq(SysDept::getStatus, queryDTO.getStatus());
        }
        
        // 排除已删除的记录
        wrapper.eq(SysDept::getDeleted, 0);
        
        // 执行分页查询
        IPage<SysDept> deptPage = this.page(page, wrapper);
        
        // 转换为VO对象
        Page<DeptVO> voPage = new Page<>(deptPage.getCurrent(), deptPage.getSize(), deptPage.getTotal());
        voPage.setRecords(deptPage.getRecords().stream().map(this::convertToVO).toList());
        
        return voPage;
    }
    
    @Override
    public Result getDeptByUserId() {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("用户ID：{}", userId);
        // 查询用户信息
        SysUser user = userMapper.selectById(userId);
        if (user.getDeptId() == null) {
            return Result.failed("该用户未绑定公司");
        }
        
        // 查询部门信息
        SysDept dept = this.getById(user.getDeptId());
        if (dept == null) {
            return Result.failed("该部门不存在");
        }
        
        // 转换为VO对象
        DeptVO vo = convertToVO(dept);
        return Result.success(vo);
    }

    /**
     * 新增部门
     * @param deptSaveDTO
     */
    @Override
    public Result addDept(DeptSaveDTO deptSaveDTO) {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(deptSaveDTO, dept);
        dept.setCreateTime(new Date());
        
        // 处理备注信息
        handleRemarkInfoForSave(dept, deptSaveDTO.getRemarkInfo());
        
        Boolean result = this.save(dept);
        return Result.judge(result);
    }

    @Override
    public Result<Void> updateDeptByUserId(Long userId, DeptSaveDTO deptSaveDTO) {
        // 检查部门是否存在
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(deptSaveDTO, dept);
        
        // 检查部门是否存在
        if (dept.getId() != null && this.getById(dept.getId()) == null) {
            return Result.failed("指定的部门不存在");
        }
        
        // 更新用户对应的部门ID
        userMapper.updateDeptIdByUserId(userId, dept.getId());

        return Result.success();
    }

    @Override
    public Result<Void> updateDept(DeptSaveDTO deptSaveDTO) {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(deptSaveDTO, dept);
        dept.setUpdateTime(new Date());
        //设置修改人
        SaSession session = StpUtil.getSession();
        dept.setUpdateBy((String) session.get("name"));
        dept.setId(deptSaveDTO.getId());
        
        // 处理备注信息
        handleRemarkInfoForUpdate(dept, deptSaveDTO.getRemarkInfo());
        
        boolean result = this.updateById(dept);
        return Result.judge(result);
    }

    @Override
    public Result<Void> deleteDept(Long id) {
        boolean result = this.removeById(id);
        return Result.judge(result);
    }

    @Override
    public Result<Void> deleteDeptBatch(List<Long> ids) {
        boolean result = this.removeByIds(ids);
        return Result.judge(result);
    }
    
    @Override
    public DeptVO getDeptDetail(Long deptId) {
        SysDept dept = this.getById(deptId);
        if (dept == null) {
            return null;
        }
        return convertToVO(dept);
    }
    
    /**
     * 将SysDept转换为DeptVO
     * @param dept SysDept实体
     * @return DeptVO对象
     */
    private DeptVO convertToVO(SysDept dept) {
        DeptVO vo = new DeptVO();
        BeanUtils.copyProperties(dept, vo);
        
        // 解析remark字段
        if (dept.getRemark() != null && !dept.getRemark().isEmpty()) {
            try {
                JSONObject remarkJson = JSONUtil.parseObj(dept.getRemark());
                RemarkInfo remarkInfo = new RemarkInfo();
                
                remarkInfo.setApplyReason(remarkJson.getStr("applyReason"));
                remarkInfo.setAuditReason(remarkJson.getStr("auditReason"));
                remarkInfo.setApplyTime(remarkJson.getStr("applyTime"));
                remarkInfo.setAuditTime(remarkJson.getStr("auditTime"));
                remarkInfo.setApplicant(remarkJson.getStr("applicant"));
                remarkInfo.setAuditor(remarkJson.getStr("auditor"));
                
                // 解析历史记录
                JSONArray historyArray = remarkJson.getJSONArray("history");
                if (historyArray != null) {
                    List<RemarkHistory> historyList = new ArrayList<>();
                    for (int i = 0; i < historyArray.size(); i++) {
                        JSONObject historyItem = historyArray.getJSONObject(i);
                        RemarkHistory history = new RemarkHistory();
                        history.setReason(historyItem.getStr("reason"));
                        history.setOperator(historyItem.getStr("operator"));
                        history.setTime(historyItem.getStr("time"));
                        historyList.add(history);
                    }
                    remarkInfo.setHistory(historyList);
                }
                
                vo.setRemarkInfo(remarkInfo);
            } catch (Exception e) {
                log.error("解析备注信息失败", e);
            }
        }
        
        return vo;
    }
    
    /**
     * 处理新增时的备注信息
     * @param dept 部门实体
     * @param remarkInfo 备注信息
     */
    private void handleRemarkInfoForSave(SysDept dept, RemarkInfo remarkInfo) {
        if (remarkInfo != null) {
            JSONObject remarkJson = JSONUtil.createObj();
            remarkJson.set("applyReason", remarkInfo.getApplyReason());
            remarkJson.set("applyTime", remarkInfo.getApplyTime() != null ? remarkInfo.getApplyTime() : new Date().toString());
            remarkJson.set("applicant", remarkInfo.getApplicant());
            
            dept.setRemark(remarkJson.toString());
        }
    }
    
    /**
     * 处理更新时的备注信息（支持历史记录）
     * @param dept 部门实体
     * @param remarkInfo 备注信息
     */
    private void handleRemarkInfoForUpdate(SysDept dept, RemarkInfo remarkInfo) {
        if (remarkInfo != null) {
            JSONObject remarkJson = JSONUtil.createObj();
            
            // 如果已有备注，先解析
            if (dept.getRemark() != null && !dept.getRemark().isEmpty()) {
                try {
                    JSONObject existingRemark = JSONUtil.parseObj(dept.getRemark());
                    remarkJson.putAll(existingRemark);
                    
                    // 如果有新的审核信息，将旧的申请审核信息移入历史记录
                    if (remarkInfo.getAuditReason() != null) {
                        // 创建历史记录数组（如果不存在）
                        JSONArray historyArray = existingRemark.getJSONArray("history");
                        if (historyArray == null) {
                            historyArray = new JSONArray();
                        }
                        
                        // 创建历史记录对象
                        JSONObject historyItem = JSONUtil.createObj();
                        historyItem.set("reason", "申请：" + existingRemark.getStr("applyReason", "") + 
                                          "，审核：" + existingRemark.getStr("auditReason", ""));
                        historyItem.set("operator", existingRemark.getStr("applicant", "") + "->" + 
                                          existingRemark.getStr("auditor", ""));
                        historyItem.set("time", existingRemark.getStr("applyTime", "") + "->" + 
                                          existingRemark.getStr("auditTime", ""));
                        
                        // 添加到历史记录
                        historyArray.add(historyItem);
                        remarkJson.set("history", historyArray);
                    }
                } catch (Exception e) {
                    log.error("解析现有备注失败", e);
                }
            }
            
            // 更新当前申请信息（如果有）
            if (remarkInfo.getApplyReason() != null) {
                remarkJson.set("applyReason", remarkInfo.getApplyReason());
                remarkJson.set("applyTime", remarkInfo.getApplyTime() != null ? 
                              remarkInfo.getApplyTime() : new Date().toString());
                remarkJson.set("applicant", remarkInfo.getApplicant());
            }
            
            // 更新当前审核信息（如果有）
            if (remarkInfo.getAuditReason() != null) {
                remarkJson.set("auditReason", remarkInfo.getAuditReason());
                remarkJson.set("auditTime", remarkInfo.getAuditTime() != null ? 
                              remarkInfo.getAuditTime() : new Date().toString());
                remarkJson.set("auditor", remarkInfo.getAuditor());
            }
            
            dept.setRemark(remarkJson.toString());
        }
    }
}